package com.xunqi.activemq.queue;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.ScheduledMessage;
import org.junit.Test;

import javax.jms.*;

/**
 * @Description: 生产者延时投递
 * @Created: with IntelliJ IDEA.
 * @author: 夏沫止水
 * @createTime: 2020-06-26 10:28
 **/
public class JmsProduct_DelayAndSchedule {

    //默认tcp协议
    public static final String ACTIVEMQ_URL = "tcp://192.168.77.130:61616";
    public static final String QUEUE_NAME = "Queue-延迟投递";

    @Test
    public void product() throws JMSException {

        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(ACTIVEMQ_URL);
        Connection connection = activeMQConnectionFactory.createConnection();
        connection.start();

        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Queue queue = session.createQueue(QUEUE_NAME);
        MessageProducer messageProducer = session.createProducer(queue);

        long delay = 3 * 1000;      //延迟投递的时间
        long period = 4 * 1000;     //每次投递的时间间隔
        int repeat = 5;                     //投递的次数

        for (int i = 1; i <= 3; i++) {
            TextMessage textMessage = session.createTextMessage("delay message---" + i);//理解为一个字符串

            textMessage.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, delay);
            textMessage.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_PERIOD, period);
            textMessage.setIntProperty(ScheduledMessage.AMQ_SCHEDULED_REPEAT, repeat);

            messageProducer.send(textMessage);
        }

        messageProducer.close();
        session.close();
        connection.close();
        System.out.println("****消息发布到MQ队列完成");

    }
}
